//
//  JWFeaturedController.m
//  见闻新闻
//
//  Created by brother on 16/2/28.
//  Copyright © 2016年 JoanBoat. All rights reserved.
//

#import "JWFeaturedController.h"
#import "JWFeatured.h"
#import "JWFeaturedCell.h"
#import "JWWebController.h"
#import "JWButton.h"
#import "HJCarouselViewLayout.h"
#import "JWFMDBHostpotTool.h"



@interface JWFeaturedController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,MBProgressHUDDelegate,featuredDelegate,BtnDelegate>
@property (weak, nonatomic)UICollectionView *myCollectionView;
@property (nonatomic ,strong)NSMutableArray *newsMutArray;

@property (nonatomic ,copy)NSString *max_id;

@property (nonatomic ,copy)NSString *min_id;

@property (nonatomic,strong)JWFeatured *feature;

@property (nonatomic ,assign)BOOL isRefresh;

@property (nonatomic,weak)JWButton *redView;

@property (nonatomic ,assign)BOOL isShow;

@property (nonatomic ,copy)NSString *appkey;



@end

@implementation JWFeaturedController

- (NSMutableArray *)newsMutArray {
    if (_newsMutArray == nil) {
        _newsMutArray = [NSMutableArray array];
    }
    return _newsMutArray;
}

static NSString *ID = @"cell";

- (void)viewDidLoad {
    [super viewDidLoad];
    self.appkey = @"jw10000001";
    if ([JWFMDBHostpotTool hostpotWithAppkey:self.appkey].count > 0) {
        self.newsMutArray = [JWFMDBHostpotTool hostpotWithAppkey:self.appkey];
        [self.myCollectionView reloadData];
        NSLog(@"11111");
    }else {
        [self AFNNews];
    }
    [self foundWithCollectionViewAndLayout];
    // Do any additional setup after loading the view.
}
#pragma mark - 创建UICollectionView
- (void)foundWithCollectionViewAndLayout {
    HJCarouselViewLayout *carouseLayout = [[HJCarouselViewLayout alloc]initWithAnim:HJCarouselAnimRotary];

    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height-64-49) collectionViewLayout:carouseLayout];
    collectionView.backgroundColor = [UIColor blackColor];
    
    carouseLayout.itemSize = CGSizeMake(collectionView.frame.size.width, collectionView.frame.size.height*0.6);
    
    collectionView.dataSource = self;
    collectionView.delegate = self;
    [collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([JWFeaturedCell class]) bundle:nil] forCellWithReuseIdentifier:ID];
    
    [self.view addSubview:collectionView];
    
    self.myCollectionView = collectionView;
    
    self.myCollectionView.showsHorizontalScrollIndicator = NO;
    
    self.myCollectionView.showsVerticalScrollIndicator = NO;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidAppear:(BOOL)animated {

    [super viewDidAppear:animated];
    [self pullRefreshData];
    [self loadButtonView];
}
#pragma mark - 数据请求
- (void)AFNNews {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"正在加载";
    hud.delegate = self;
    NSString *str = @"http://1.zhixinnews.applinzi.com/Home/Hotspot/queryhotspos";
    NSDictionary *dic = @{@"appKey":self.appkey};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:str parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
        
        NSMutableArray *listArray = responseObject[@"data"];
        NSMutableArray *mutArray = [NSMutableArray array];
        
        [listArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
           JWFeatured *featured = [[JWFeatured alloc]initWithDic:obj];
            if ([JWFMDBHostpotTool hostpotWithWhereId:featured.rd_id].count > 0) {
                NSLog(@"存在 aaa");
            }else {
                BOOL sussecc = [JWFMDBHostpotTool insertNewsWithFeatured:featured];
                if (sussecc) {
                    NSLog(@"成功aa");
                }else {
                    NSLog(@"失败");
                }
            }
            [mutArray addObject:featured];
        }];
        self.newsMutArray = mutArray;
        [hud hide:YES];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error.code == -1009) {
            NSLog(@"222");
        }else {
           [hud hide:YES];
        }
    }];
}

#pragma mark -上拉刷新数据
- (void)pullRefreshData {
    self.myCollectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (self.newsMutArray.count > 0) {
            
            JWFeatured *feature = [self.newsMutArray lastObject];
            self.max_id = feature.rd_id;
            
        }else {
            return ;
        }
        [self shanglaRefreshAFFFFFF:self.max_id];
        
        [self.myCollectionView.mj_footer endRefreshing];

    }];
}
- (void)shanglaRefreshAFFFFFF:(NSString *)max_id{

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString *str = @"http://1.zhixinnews.applinzi.com/Home/Hotspot/showhotspotPage";
    NSDictionary *dic = @{@"max_id":max_id};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:str parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSArray *dataArray = responseObject[@"data"];
         if ([self.appkey isEqualToString:dataArray[0][@"rd_appkey"]]) {
            NSMutableArray *mutArray = [NSMutableArray array];
            
            [dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                JWFeatured *feature = [[JWFeatured alloc]initWithDic:obj];
                [mutArray addObject:feature];
            }];
            
            NSMutableArray *tempArray = [NSMutableArray array];
            if (mutArray.count > 0) {
                [mutArray removeObjectAtIndex:0];
            }
            [tempArray addObjectsFromArray:self.newsMutArray];
            [tempArray addObjectsFromArray:mutArray ];
            self.newsMutArray = tempArray;
            [hud hide:YES];
            [self.myCollectionView reloadData];
         }else {
             [hud hide:YES];
            [self.myCollectionView reloadData];
         }

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error.code == -1009) {
            return ;
        }else {
            [hud hide:YES];
            [self.myCollectionView reloadData];
        }
        
    }];
}
- (void)hudWasHidden:(MBProgressHUD *)hud {
    if (self.newsMutArray.count > 0) {
        [self.myCollectionView reloadData];
        [self.myCollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] atScrollPosition:UICollectionViewScrollPositionTop animated:NO];
    }
    
}
#pragma mark - 数据显示
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.newsMutArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    JWFeaturedCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.featured = self.newsMutArray[indexPath.item];
    return cell;
}
#pragma mark itme 的size


#pragma mark - 点击事件
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [self yemiantiaozhuan];
    self.feature = self.newsMutArray[indexPath.row];
}

- (void)yemiantiaozhuan{
    JWWebController *webControl = [[JWWebController alloc]initWithNibName:@"JWWebController" bundle:nil];
    webControl.delegate = self;
    [self.navigationController pushViewController:webControl animated:YES];

}
- (JWFeatured *)featuredWith{
    return self.feature;
}

#pragma mark - 自定义按钮创建
- (void)loadButtonView {
        JWButton *buttonView = [JWButton buttonView];
        buttonView.delegate = self;
        self.redView = buttonView;
        [self.view addSubview:buttonView];
}
#pragma mark - 代理回调
-(void)apppkey:(NSString *)key {
    self.appkey = key;
    NSLog(@"%@",self.appkey);
    if ([JWFMDBHostpotTool hostpotWithAppkey:self.appkey].count > 0) {
        self.newsMutArray = [JWFMDBHostpotTool hostpotWithAppkey:self.appkey];
        [self.myCollectionView reloadData];
        NSLog(@"AAAAAA");
    }else {
       [self AFNNews];
    }
    
}


- (IBAction)xibButtonBtnClick:(id)sender {

    if (self.redView.alpha == 0) {
        self.redView.alpha = 1;
        self.isShow = YES;
        [self.redView showItmes:self.isShow];
        //[UIView transitionWithView:self.redView duration:1.0f options:UIViewAnimationOptionTransitionCrossDissolve animations:nil completion:nil];
    }else {
        self.redView.alpha = 0;
        self.isShow = NO;
        //[UIView transitionWithView:self.redView duration:1.0f options:UIViewAnimationOptionTransitionCrossDissolve animations:nil completion:nil];
    }

}


@end
